var util = require("./util.js");
export default class Request {
	http(param) {
		// 请求参数
		var url = param.url,
			method = param.method,
			header = {},
			data =  param.data || {},
			token = param.token || "",
			isencode=param.data.isencode,
			hideLoading = param.hideLoading || false;

		//拼接完整请求地址
		if(url==''){
			var nginxurl = uni.getStorageSync('nginxurl')
			var webname = uni.getStorageSync('webname')
			var requestUrl = nginxurl+'/' + webname + '/assaas'
		}else{
			var requestUrl = url
		}

		//请求方式:GET或POST
		if (method) {
			method = method.toUpperCase();
			if (method == "POST") {
				header = {'content-type': "application/x-www-form-urlencoded"};
			} else {
				header = {'content-type': "application/json"};
			}
		}
		
		//加载圈
		if (!hideLoading) {
			uni.showLoading({
				title: '加载中...',
				mask:true
			});
		}
		// 返回promise
		return new Promise((resolve, reject) => {
			// 请求
			uni.request({
				url: requestUrl,
				data: data,
				method: method,
				header: header,
				success: (res) => {
					// 判断 请求api 格式是否正确
					console.log(res)
					if (res.statusCode && res.statusCode != 200) {
						uni.showToast({
							title: "api错误" + res.errMsg,
							icon: 'none'
						});
						return;
					}
					
					
					if((isencode+'')=='undefined'){
						data = JSON.parse(util.decode(res.data))
					}else{
						data = res.data
					}
					
					if(data.ERRTEXT!=''){
						uni.showModal({
							title:'提示1',
							content:data.ERRTEXT,
							showCancel:false
						})
						return;
					}
					
					// code判断:200成功,不等于200错误
					if (data.DATA.rtn == -1) {
						uni.showModal({
							title:'提示2',
							content:data.DATA.errmsg,
							showCancel:false
						})
						return;
					}
					if (data.DATA.rtn == -99) {
						var dbname = uni.getStorageSync('dbname');
						var productname = uni.getStorageSync('productname');
						var terminaltype = uni.getStorageSync('terminaltype');
						uni.reLaunch({url: '/pages/first/first?dbname=' + dbname + '&productname=' + productname + '&terminaltype=' +terminaltype});
						return;
					}
					// 将结果抛出
					resolve(data)
					
				},
				//请求失败
				fail: (e) => {
					console.log(e)
					uni.showToast({
						title: "" + e.errMsg,
						icon: 'none'
					});
					resolve(e.errMsg);
				},
				//请求完成
				complete() {
					//隐藏加载
					if (!hideLoading) {
						uni.hideLoading();
					}
					resolve();
					return;
				}
			})
		})
	}
}
